<?php
/*
 * @Author: your name
 * @Date: 2021-09-21 16:46:35
 * @LastEditTime: 2022-02-08 18:05:49
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /nlog/app/Http/Controllers/AdminController/Login.php
 */

namespace App\Http\Controllers\admin_controller;

use Illuminate\Support\Facades\Request;

class WriteLog extends BaseController
{

    /**
     * @description: 日志
     */
    public static function index()
    {
       
        \Illuminate\Support\Facades\DB::listen(     //监听mysql语句写入日志
            function ($sql){
                $_POST['WEBSOCKET_SERVER']->task(['handle'=>'mysqlLog', 'statements'=> $sql , 'operation_log' =>  array(
                    // 'statements' => vsprintf($query, $sql->bindings),                             //mysql语句
                    'operation_content' => json_encode( $_POST['REQUEST_ALL'][Request::method()]),   //操作的内容
                    'path'   => Request::path(),                        //操作的路由
                    'method' => Request::method(),                      //操作的方法
                    'ip'     => $_SERVER['X-REAL-IP'],                  //操作的IP
                    'operation_id' =>   parent::getAdminId_() ,         //操作人id
                )  
                ]
            );


                foreach ($sql->bindings as $i => $binding) {
                    if ($binding instanceof \DateTime) {
                        $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                    } else {
                        if (is_string($binding)) {
                            $sql->bindings[$i] = "'$binding'";
                        }
                    }
                }
                $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
                $operation_log =  array(
                    'statements' => vsprintf($query, $sql->bindings),                             //mysql语句
                    'operation_content' => json_encode( $_POST['REQUEST_ALL'][Request::method()]),   //操作的内容
                    'path'   => Request::path(),                        //操作的路由
                    'method' => Request::method(),                      //操作的方法
                    'ip'     => $_SERVER['X-REAL-IP'],                  //操作的IP
                    'operation_id' =>   parent::getAdminId_() ,         //操作人id
                );
                $sql_grammar  =  ltrim(vsprintf($query, $sql->bindings));      //去除左边空格 mysql语句
                $operation = strtoupper( substr(   $sql_grammar , 0 , strpos(  $sql_grammar , " ") ) );
                if(  $operation == "UPDATE" ){
                    $operation_log['operation'] = '编辑';     
                }else if( $operation == "INSERT") {
                    $operation_log['operation'] = '添加';   
                }

                

                // var_dump( $operation_log);





                



                
            
            } );
    }


    
}
